//
//  MusicManager.m
//  SleepingElf
//
//  Created by karong on 2023/10/17.
//

#import "MusicManager.h"
#import <SJMP3Player.h>

@interface MusicManager ()<SJMP3PlayerDelegate>
@property (nonatomic, strong) SJMP3Player *player;
@property (nonatomic, assign) BOOL isManagerPlaying;
@end

@implementation MusicManager
/// 初始化失败
- (void)mp3Player:(SJMP3Player *)player initializationFailed:(NSError *)error {
    
}

/// 播放完毕的回调
- (void)mp3PlayerDidFinishPlaying:(SJMP3Player *)player; {
    if (self.type == 0) {
        if (![[PlayerManager shared] next]) {
            [self playWithMusic:self.music];
        }
    }
    else if (self.type == 1) {
        [self playWithMusic:self.music];
    }
    else if (self.type == 2) {
        [self keepAlivePlay];
    }
}

- (void)playWithMusic:(MusicModel *)music {
    self.music = music;
    self.isManagerPlaying = YES;
    if ([music.url containsString:@"http"]) {
        self.player = [SJMP3Player playerWithURL:[NSURL URLWithString:[music.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    }
    else if (!SEIsNullOrEmpty(music.url) && music.url.length < 5) {
        NSString *wavPath = [[NSBundle mainBundle]pathForResource:music.url ofType:@"mp3"];
        NSURL *soundURL = [NSURL fileURLWithPath:wavPath];
        self.player = [SJMP3Player playerWithURL:soundURL];
    }
    self.player.volume = 1;
    self.player.delegate = self;
    [appConfig addHistoryMusic:music];
}

- (void)keepAlivePlay {
    MusicModel * music = [MusicModel new];
    music.url = @"gqs";
    self.music = music;
    self.isManagerPlaying = YES;
    NSString *wavPath = [[NSBundle mainBundle]pathForResource:music.url ofType:@"mp3"];
    NSURL *soundURL = [NSURL fileURLWithPath:wavPath];
    self.player = [SJMP3Player playerWithURL:soundURL];
    self.player.volume = 0;
    self.player.delegate = self;
}

- (void)pause {
    [self.player pause];
    self.isManagerPlaying = NO;
}

- (void)resume {
    if (self.player) {
        [self.player resume];
    }
    else {
        [self playWithMusic:self.music];
    }
    self.isManagerPlaying = YES;
}

- (void)stop {
    [self.player stop];
    self.isManagerPlaying = NO;
}

- (BOOL)isPlaying {
    return self.player.isPlaying || self.isManagerPlaying;
}

- (CGFloat)playerVolume {
    return self.player.volume;
}

- (void)changePlayerVolume:(float)volume {
    self.player.volume = volume;
}
@end
